package com.zhangwei.yueshijia.view.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.zhangwei.yueshijia.R;
import com.zhangwei.yueshijia.api.ExceptionHandle;
import com.zhangwei.yueshijia.base.MvpFragment;
import com.zhangwei.yueshijia.bean.home.Banner;
import com.zhangwei.yueshijia.bean.home.Goods;
import com.zhangwei.yueshijia.presenter.HomePresenter;
import com.zhangwei.yueshijia.utils.ImageLoader;
import com.zhangwei.yueshijia.view.adapter.GoodsAdapter;
import com.zhangwei.yueshijia.view.impl.HomeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Pulltorefresh   https://github.com/HomHomLin/Android-PullToRefreshRecyclerView
 * 传统动画刷新
 * https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh
 * https://github.com/jianghejie/XRecyclerView
 *
 * 下拉刷新                        SwipRefreshLayout
 * Dialog
 * https://github.com/cymcsg/UltimateRecyclerView(学习难度大)
 * https://github.com/supercwn/SuperRecycleView
 *
 * 轮播实现
 * https://github.com/saiwu-bigkoo/Android-ConvenientBanner
 * https://github.com/youth5201314
 * https://github.com/Jude95/RollViewPager
 *
 * 开源库网站 https://github.com/Trinea/android-open-project#%E5%9B%9Bviewpager-gallery
 */
public class HomeFragment extends MvpFragment<HomePresenter>
        implements SuperRecyclerView.LoadingListener
        , HomeView
        , SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.home_recycler_view)
    SuperRecyclerView homeRecyclerView;
    GoodsAdapter goodsAdapter;
    private ArrayList<Goods> data = new ArrayList<>();
    private int page = 1;
    private HeadViewHolder vh;

    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public HomePresenter initPresenter() {
        return new HomePresenter();
    }

    @Override
    public void initView() {
        vh = new HeadViewHolder();
        LinearLayoutManager llm = new LinearLayoutManager(context);
        homeRecyclerView.setLayoutManager(llm);
        homeRecyclerView.setRefreshEnabled(true); // 开启下拉刷新
        homeRecyclerView.setLoadMoreEnabled(true); //开启下拉刷新   默认开启
        homeRecyclerView.setLoadingListener(this);
//        效果请查看动画库  https://github.com/81813780/AVLoadingIndicatorView
//        homeRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.);  上拉加载更多的动画
        homeRecyclerView.setArrowImageView(R.mipmap.ic_loading); //设置下拉刷新的图标

        goodsAdapter = new GoodsAdapter(context, data);
        goodsAdapter.addHeaderView(vh.headView);
        homeRecyclerView.setAdapter(goodsAdapter);
        //自动刷新
//        homeRecyclerView.setRefreshing(true);
    }

    @Override
    public void initData() {
        prsenter.getHomeData(getRequestParams());
    }

    @Override
    public void onSuccess(List<Goods> bean, boolean hasmore, int pageTotal) {
        if (page == 1 && !data.isEmpty()) {
            data.clear();
            homeRecyclerView.setLoadMoreEnabled(true);
        }
        if (!hasmore && page >= pageTotal) {
            homeRecyclerView.setLoadMoreEnabled(false);
        }
        data.addAll(bean);
        goodsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccessHeadData(List<Banner> banners) {
        vh.banners.clear();
        vh.banners.addAll(banners);
        vh.bannerView.notifyDataSetChanged();
    }
        
    @Override
    public void onShow() {

    }

    @Override
    public void onFial(ExceptionHandle.ResponeThrowable e) {

    }

    @Override
    public void onFinish() {
        homeRecyclerView.completeRefresh();
        homeRecyclerView.completeLoadMore();
    }

    public HashMap<String, String> getRequestParams() {
        HashMap<String, String> map = new HashMap<>();
        map.put("act", "app");
        map.put("op", "index1");
        map.put("client", "android");
        map.put("curpage", String.valueOf(page));
        map.put("token", "749a036dc06ae8b3a120848995a9f306");
        map.put("key", "f5492f263ab68e5b9c85b2a26c6f820e");
        return map;
    }

    @Override
    public void onRefresh() {
        page = 1;
        initData();
    }

    @Override
    public void onLoadMore() {
        page++;
        initData();
    }


    /**
     * 注解的作用
     * 配合反射使用
     * 预生成代码--apt
     */
    public class HeadViewHolder {
        @BindView(R.id.home_head_banner)
        ConvenientBanner bannerView;

        ArrayList<Banner> banners = new ArrayList<>();

        private View headView;


        public HeadViewHolder() {
            headView = LayoutInflater.from(context).inflate(R.layout.home_head_layout, null);
            ButterKnife.bind(this, headView);
            bannerView.setPages(new BannerCreator(), banners)
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .setPageIndicator(new int[]{R.mipmap.ic_page_indicator_focused, R.mipmap.ic_page_indicator});
        }

        public class BannerCreator implements CBViewHolderCreator<BannerViewHolder> {
            @Override
            public BannerViewHolder createHolder() {
                return new BannerViewHolder();
            }
        }

        public class BannerViewHolder implements Holder<Banner> {


            private ImageView imageView;

            @Override
            public View createView(Context context) {
                imageView = new ImageView(context);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                return imageView;
            }


            @Override
            public void UpdateUI(Context context, int position, Banner data) {
                ImageLoader.getSingleton().displayImage(data.getAdvertImg(), context, imageView);

            }
        }


        /**
         * 使用反射技术必须先获得类或者接口的Class
         *
         * @param obj
         * @param view
         */
//    public void bind(Activity activity) {
//        Class<?> cls = activity.getClass();
//        Field[] declaredFields = cls.getDeclaredFields();
//
//        for (Field f : declaredFields) {
//
//            BindView annotation = f.getAnnotation(BindView.class);
//            int id = annotation.value();
//
//
//            View viewById = activity.findViewById(id);
//
//            f.setAccessible(true);
//            f.set(activity,viewById);
//
//
//        }


    }

    @Override
    public void onResume() {
        super.onResume();
        vh.bannerView.startTurning(2 * 1000);
    }

    @Override
    public void onPause() {
        super.onPause();
        vh.bannerView.stopTurning();
    }
}
